<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { onMounted, onBeforeUnmount, watch, ref, reactive } from 'vue'
import * as echarts from 'echarts'
import { CaretRight } from '@element-plus/icons-vue'
import { headersStore } from '@/stores/apiHeader'
import { DEFAULT_ECHARTS_FONTSIZE,DIALOG_ECHARTS_FONTSIZE } from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const headerStore = headersStore()
const { language_id } = storeToRefs(headerStore)

const fontSize = dialogInfo.visible ? DIALOG_ECHARTS_FONTSIZE : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()
watch(
  () => props.chartData,
  () => {
    paginate.currentPage = 1
    createChart()
  },
  { deep: true }
)

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}

// 返回值是千分位逗号隔开的字符串
const numberFormat = (num: number) => {
  if (num == undefined) {
    return ''
  }
  return num.toString().replace(/\d+/, function (n) {
    // 先提取整数部分
    return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
      return $1 + ','
    })
  })
}

const paginate = reactive({
  currentPage: 1,
  pageSize: 0,
  total: 0,
  totalPage: 0,
})

// 向右箭头翻页
const nextPage = () => {
  // 如果paginate.currentPage小于paginate.totalPage 加1
  if (paginate.currentPage < paginate.totalPage) {
    paginate.currentPage += 1
  } else {
    paginate.currentPage = 1
  }
  createChart()
}

let myChart: any
const createChart = () => {
  myChart = echarts.getInstanceByDom(
    document.getElementById(props.chartData.name)
  )
  //如果为空 则正常进行渲染 反之 不再进行初始化
  if (myChart == null) {
    myChart = echarts.init(document.getElementById(props.chartData.name))
  }
  myChart.dispatchAction({
    type: 'hideTip',
  })

  // 如果传入值有props.chartData.paginate,则进行分页处理
  let nameArr = []
  let valueArr = []
  if (props.chartData.paginate) {
    paginate.total = props.chartData.data.length
    paginate.pageSize = props.chartData.paginate.pageSize || 5
    paginate.totalPage = Math.ceil(paginate.total / paginate.pageSize)
    const start = (paginate.currentPage - 1) * paginate.pageSize
    const end = paginate.currentPage * paginate.pageSize
    const data = props.chartData.data.slice(start, end)
    // 获取对象的name,组成新数组
    nameArr = data.map((item: any) => {
      return item.name
    })
    // 获取对象的value,组成新数组
    valueArr = data.map((item: any) => {
      return item.value3 || item.value // 如果有value3,则取value3,value3是除以10000的值
    })
  } else {
    // 获取对象的name,组成新数组
    nameArr = props.chartData.data.map((item: any) => {
      return item.name
    })
    // 获取对象的value,组成新数组
    valueArr = props.chartData.data.map((item: any) => {
      return item.value3 || item.value // 如果有value3,则取value3,value3是除以10000的值
    })
  }

  const colors = [
    { offset: 0, color: '#5640e2' },
    { offset: 0.3, color: '#5640e2' },
    { offset: 1, color: '#0abafe' },
  ]
  if (props.chartData.colors) {
    colors.splice(0, colors.length, ...props.chartData.colors)
  }

  const option = {
    grid: {
      left: '5%',
      right: '5%',
      bottom: '6%',
      top: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: nameArr,
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: '#fff', // 设置 X 轴标签字体颜色
        fontSize: changePixelSize(fontSize),
        interval: 0, // 强制显示所有标签
        offset: 1,
        rotate: props.chartData.titleRotate || 0, // 倾斜
        align: props.chartData.titleRotate ? 'right' : 'center',
        formatter:dialogInfoVisible==false? function (str: any) {
          // 中文算2,英文算1,数到maxLength截取,然后打...
          let count = 0
          let result = ''
          const maxLength = props.chartData.titleRotate ? 14 : 8

          for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i)
            count += /[\u4E00-\u9FA5]/g.test(char) ? 2 : 1

            if (count > maxLength) {
              result += '...'
              break
            }

            result += char
          }
          return result
        }:function (str: any) {
          // 中文算2,英文算1,数到maxLength截取,然后打...
          let count = 0
          let result = ''
          const maxLength = props.chartData.titleRotate ? 14 : 8

          for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i)
            count += /[\u4E00-\u9FA5]/g.test(char) ? 1 : 1

            if (count > maxLength) {
              result += '...'
              break
            }

            result += char
          }
          return result
        },
      },
    },
    yAxis: {
      type: 'value',
      scale: true,
      axisLine: {
        show: true,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#2b3f7c',
          type: [5, 10],
        },
      },
      axisLabel: {
        fontSize: changePixelSize(fontSize),
        color: '#FFFFFF',
        margin: changePixelSize(5), // 调整标签与轴线的距离
        formatter: props.chartData?.series?.label?.appendText
          ? '{value}' + props.chartData?.series?.label?.appendText
          : null,
      },
    },
    series: [
      {
        type: 'bar',
        stack: 'total',
        data: valueArr,
        barWidth: changePixelSize(20),
        emphasis: {
          focus: 'none',
          itemStyle: {
            opacity: 1,
            shadowBlur: 8,
            shadowColor: 'rgba(33, 50, 235, 1)',
          },
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 1, 0, 0, colors),
          opacity: 0.8,
        },
        label: {
          show: props.chartData?.series?.label?.show ? true : false,
          position: 'top',
          color: '#fff',
          fontSize: changePixelSize(fontSize),
          formatter: function (params: any) {
            return (
              params.value + (props.chartData?.series?.label?.appendText || '')
            )
          },
        },
      },
    ],
    // 鼠标放上去的
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'none',
      },
      backgroundColor: 'rgba(0,0,0,0.7)', //默认值，提示背景颜色，默认为透明度为0.7的黑色
      textStyle: {
        fontSize: changePixelSize(fontSize),
        color: '#fff', //设置文字颜色
      },
      borderWidth: 0,
      padding: changePixelSize(8),
      confine: true,
      formatter: function (params: any) {
        const param = params[0]
        if (!param) {
          return ''
        }
        let target = ''
        for (let i = 0; i < props.chartData.data.length; i++) {
          if (props.chartData.data[i].name == param.name) {
            // 如果有value2显示value2,如果没有就显示value
            const nameStr =
              '<div style="display:flex;justify-content: space-between;align-items:center;max-width:' +
              changePixelSize(200) +
              'px;"><div style="white-space: pre-wrap;word-wrap:break-word;word-break:break-all;max-width:' +
              changePixelSize(150) +
              'px;">' +
              param.name +
              '</div><div>'
            target =
              nameStr +
              ' : ' +
              (props.chartData.data[i].value2 != undefined
                ? props.chartData.data[i].value2
                : numberFormat(props.chartData.data[i].value) +
                  (props.chartData?.series?.label?.appendText ||
                    props.chartData?.suffix ||
                    '')) +
              '</div>'
          }
        }
        return target
      },
    },
  }
  // 绘制图表
  myChart.setOption(option)
}
onMounted(() => {
  setTimeout(() => {
    createChart()
  }, 300)
})

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'bottom-box': chartData.position == 'bottom',
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <el-button
      class="next-button"
      type="primary"
      :icon="CaretRight"
      @click="nextPage"
      v-if="props.chartData.paginate && paginate.totalPage > 1"
    />
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>
<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(
    260px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
  .chart {
    width: 100%;
    height: 100%;
  }
  .test-btn {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}
.bottom-box {
  height: calc(
    210px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
.dialog-box {
  height: calc(
    500px - 45px
  );
}
.next-button {
  width: 20px;
  height: 20px;
  position: absolute;
  opacity: 0.9;
  right: 2%;
  top: 50%;
  transform: translateY(-50%);
  z-index: 999;
  background-color: #556fb5;
  color: #00eef0;
  border: 0;
}
</style>
